<template>
    <div class="edit-product-container">
        <h2>编辑商品</h2>
        <div v-if="loading" class="loading-state">
            <div class="spinner"></div>
            <p>正在加载商品详情...</p>
        </div>
        <div v-else-if="error" class="error-state">
            <p>⚠️ 加载失败：{{ error }}</p>
            <button @click="fetchProductDetails" class="retry-btn">重试</button>
        </div>
        <template v-else>
            <form @submit.prevent="saveProduct" class="edit-form">
                <div class="form-group">
                    <label for="title">标题</label>
                    <input type="text" id="title" v-model="product.title" required />
                </div>
                <div class="form-group">
                    <label for="description">描述</label>
                    <textarea id="description" v-model="product.description" required></textarea>
                </div>
                <div class="form-group">
                    <label for="price">价格</label>
                    <input type="number" id="price" v-model.number="product.price" step="0.01" required />
                </div>
                <div class="form-group">
                    <label for="stock">库存</label>
                    <input type="number" id="stock" v-model.number="product.stock" required />
                </div>
                <div class="form-group">
                    <label for="categoryname">类别</label>
                    <input type="text" id="categoryname" v-model="product.categoryname" required />
                </div>
                <div class="form-group">
                    <label for="onsale">上架状态</label>
                    <select id="onsale" v-model="product.onsale">
                        <option :value="true">启用</option>
                        <option :value="false">停用</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="productimg">商品图片 URL</label>
                    <input type="text" id="productimg" v-model="product.productimg" />
                </div>
                <div class="form-group">
                    <label for="adimg">广告图片 URL</label>
                    <input type="text" id="adimg" v-model="product.adimg" />
                </div>
                <div class="form-actions">
                    <button type="submit" class="save-btn">保存</button>
                    <button class="back-btn" @click="goBack">返回</button>
                </div>
            </form>
        </template>
        <Notification v-if="notification.message" :message="notification.message" :type="notification.type" />
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getProductById, updateProduct,addAdimg } from '../../api/product';
import Notification from '../../components/Notification.vue';

const route = useRoute();
const router = useRouter();

// 响应式数据
const product = ref(null);
const loading = ref(true);
const error = ref(null);
const notification = ref({ message: '', type: '' });

// 获取商品数据
const fetchProductDetails = async () => {
    try {
        loading.value = true;
        error.value = null;
        const productId = route.params.productid;
        console.log('根据商品id查询商品详情参数:', productId);

        if (!productId) {
            throw new Error('无效的商品ID');
        }

        const response = await getProductById(productId);
        console.log('根据商品id查询商品详情数据:', response.data);

        if (response.data?.code === 1) {
            product.value = response.data.data || null;

            if (!product.value) {
                throw new Error('商品不存在');
            }
        } else {
            throw new Error(response.data?.msg || '获取商品失败');
        }
    } catch (err) {
        console.error('商品详情加载失败:', err);
        error.value = err.message || '网络请求失败，请稍后重试';

        // 添加定时器，在2秒后自动关闭错误提示
        setTimeout(() => {
            error.value = null;
        }, 2000);
    } finally {
        loading.value = false;
    }
};

// 返回上一页
const goBack = () => {
    router.back();
};

// 保存商品信息
const saveProduct = async () => {
    try {
        loading.value = true;
        error.value = null;

        const response = await updateProduct(product.value);
        console.log('更新商品信息数据:', response.data);

        if (response.data?.code === 1) {
            notification.value = { message: '商品信息更新成功', type: 'success' };

            // 添加定时器，在2秒后自动关闭通知
            setTimeout(() => {
                notification.value = { message: '', type: '' };
            }, 2000);
        } else {
            throw new Error(response.data?.msg || '更新商品失败');
        }
    } catch (err) {
        console.error('商品信息更新失败:', err);
        notification.value = { message: err.message || '网络请求失败，请稍后重试', type: 'error' };

        // 添加定时器，在2秒后自动关闭通知
        setTimeout(() => {
            notification.value = { message: '', type: '' };
        }, 2000);
    } finally {
        loading.value = false;
    }
};

onMounted(() => {
    fetchProductDetails();
});
</script>

<style scoped>
/* 基础样式 */
.edit-product-container {
    padding: 2rem;
    min-height: 100vh;
    background: #f5f5f5;
    display: flex;
    flex-direction: column;
    align-items: center;
}

/* 表单样式 */
.edit-form {
    width: 100%;
    max-width: 600px;
    background: white;
    padding: 2rem;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    display: flex;
    flex-direction: column;
}

.form-group {
    margin-bottom: 1rem;
}

.form-group label {
    display: block;
    margin-bottom: 0.5rem;
    font-weight: bold;
    color: #333;
}

.form-group input,
.form-group textarea,
.form-group select {
    width: 100%;
    padding: 0.75rem;
    border: 1px solid #ccc;
    border-radius: 6px;
    transition: border-color 0.3s ease;
}

.form-group input:focus,
.form-group textarea:focus,
.form-group select:focus {
    border-color: #007bff;
    outline: none;
}

.form-group textarea {
    resize: vertical;
    min-height: 100px;
}

/* 保存按钮 */
.save-btn {
    margin-right: 1rem;
    padding: 0.75rem 1.5rem;
    background: #28a745;
    color: white;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

.save-btn:hover {
    background-color: #218838;
}

/* 返回按钮 */
.back-btn {
    padding: 0.75rem 1.5rem;
    background: #007bff;
    color: white;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

.back-btn:hover {
    background-color: #0056b3;
}

/* 表单操作按钮 */
.form-actions {
    display: flex;
    justify-content: flex-end;
    margin-top: 1rem;
}

/* 加载状态 */
.loading-state {
    text-align: center;
    padding: 2rem;
}

.spinner {
    width: 40px;
    height: 40px;
    margin: 0 auto 1rem;
    border: 3px solid #ddd;
    border-radius: 50%;
    border-top-color: #007bff;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    to {
        transform: rotate(360deg);
    }
}

/* 错误状态 */
.error-state {
    text-align: center;
    padding: 2rem;
    color: #dc3545;
}

.retry-btn {
    margin-top: 1rem;
    padding: 0.75rem 1.5rem;
    background: #007bff;
    color: white;
    border: none;
    border-radius: 6px;
    cursor: pointer;
}

.retry-btn:hover {
    background-color: #0056b3;
}
</style>